import Vue from 'vue'
import App from "./App.vue";
import VueRouter from "vue-router"
import VueResource from "vue-resource"
import VueImg from 'v-img';
import $ from 'jquery'
import BootstrapJs from './assets/js/bootstrap.min.js'
import Datetimepicker from './assets/js/bootstrap-datetimepicker.js'
import routes from './router'
import Config from './config.js'
import Utils from './assets/js/utils.js'
import iView from 'iview'
import './theme/iview-theme.less';

import dataTable from './constants/tableConfig.js'
import VueQuillEditor from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// import VueClipboard from 'vue-clipboard2'
import store from './store/index'
import ElementUI from 'element-ui'
import axios from 'axios'
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {
  ak: 'mj5Ztq2ugALxuBChiUgs6H0V7Cu0hfHU'
})
//开启debug模式
Vue.config.debug = true;
Vue.use(VueRouter);
Vue.use(VueResource);
Vue.use(VueImg);
// VueClipboard.config.autoSetContainer = true
// Vue.use(VueClipboard);
// Vue.use(VueEditor);
Vue.prototype.utilHelper = Config;
Vue.prototype.utils = Utils;
Vue.use(iView, {
    transfer: true,
    size: 'large'
});
Vue.use(dataTable);
Vue.use(VueQuillEditor);
Vue.use(ElementUI);

const router = new VueRouter({
	//mode: 'history',
	base: __dirname,
	routes
})

router.beforeEach(({meta,path}, from, next) => {
	var userAgent = navigator.userAgent;
	if(userAgent.indexOf('MicroMessenger') >-1) {
		if(path !== '/disableWechat') {
			return next({
				path: '/disableWechat'
			})
		} else {
			next();
		}
	}

    if("/forgetPassword" == path){
        return next();
    }
	//当返回到顶层时,将当前路径设置为下一个返回路径
	if("/index" == path || "/" == "path" || "/app" == path){
		//当返回至 /app 时,往前走一步,跳转到首页
		if("/app" == path){
			window.history.forward(1);
		}
		history.pushState(null, null, document.URL);
	}

	var isLogin = window.localStorage["1_isLogin"];
	if((!isLogin || isLogin == 'null')&& path !== '/login') {
		return next({
			path: '/login'
		})
	}
	let companyUuidUri = getQueryString('companyUuid')
	var companyUuid = window.localStorage["1_companyUuid"];
	if (companyUuid != companyUuidUri && path !== '/login') {
		window.localStorage.removeItem("1_isLogin");
		return next({
			path: '/login'
		})
	}
	next();
	if("true" == isLogin){
		//加载功能权限
		var params = {};
		params.resourcesType = 1;
		params.resourcesOrigin = 1;
		params.resourcesLevel = 1;
		var body = {};
		body.params = params;
		var url = Config.apiUrl+'/api/getUserAuthList';
		Vue.http.post(url, body).then((response)=>{
			var resData = response.body.resData;
			var resourcesList = resData.resourcesList;
			window.localStorage.setItem("userAuthResources", resourcesList);
		});
	}
})

Vue.http.interceptors.push(
(request, next) => {
	let companyUuid = getQueryString('companyUuid')
	//绑定登陆ID
	var userId=window.localStorage.getItem("1_userId");

	var requestBody=request.getBody();
	if(requestBody && requestBody.params){
		requestBody.params.loginType = 1;
	}
	if (requestBody && requestBody.params && userId) {
		if (request.url.indexOf("getLogo") == -1 && request.url.indexOf("login") == -1) {
            requestBody.params.userId=userId;
		}
	}
    request.body=requestBody;
	request.headers.set('userId',userId);
	request.headers.set('companyUuid', companyUuid);
	request.headers.set('loginType', '1');
	next((response) => {
		//验证登陆
		var isLogin = window.localStorage["1_isLogin"];
		if(!response.ok && isLogin == "true"){
			// router.replace({
			//	path: '/login'
			// });
			// window.localStorage.setItem("1_isLogin", null);
			// window.localStorage.setItem("1_userId", null);
			return;
		}
		if(isLogin == "true") {
			const data = response.body;
			if(typeof(data) == 'string' && response.ok) {
				if (data == "") {
                    router.replace({
                        path: '/login'
                    });
                    window.localStorage.setItem("1_isLogin", null);
					window.localStorage.setItem("1_userId", null);
                    return;
				} else {
                    var responseBody = JSON.parse(data);
                    var result = responseBody.result;
                    if(result == "-1") {
                        router.replace({
                            path: '/login'
                        });
                        window.localStorage.setItem("1_isLogin", null);
						window.localStorage.setItem("1_userId", null);
                        return;
                    }
				}
			}else if(typeof(data) == 'object'){
				var result=data.result;
				if(result == "-1") {
					router.replace({
						path: '/login'
					});
					return;
				}
			}
		}
	});
});

Vue.filter("substrFilter", function(value, param1, param2){
	if(value && param2 && value.length > param2 && param1 < param2){
		return value.substring(param1, param2) + "......";
	}
	return value;
})


Vue.directive('res',function(el,binding){
		if( !window.localStorage.getItem("userAuthResources")){
            el.style.display = 'none';
            return;
		}
        // var res = window.localStorage.getItem("userAuthResources").split(',');
        var res = window.localStorage.getItem("userAuthResources").split(',');
        if(res == null){
            el.style.display = 'none';
            return;
        }
		var codeStr = binding.value.code;
		var codeArr = [];
		if(codeStr.indexOf(",")){
			codeArr = codeStr.split(",");
		}else{
			codeArr.push(codeStr);
		}
        for(var i=0;i<res.length;i++){
            if(codeArr.indexOf(res[i]) > -1){
        		el.style.display = '';
                break
            }else{
                el.style.display = 'none';
            }
        }
    }
);

Vue.prototype.Log = window.console.log
Vue.config.devtools = true;
sessionStorage.prefixUrl = Config.apiUrl
sessionStorage.companyUuid =  getQueryString('companyUuid')
sessionStorage.userId =  window.localStorage.getItem("1_userId")
new Vue({
	el: "#app",
	router,
	store,
	axios,
	render: r => r(App)
  })

function getQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);

	if (r != null) {
		return unescape(r[2])
	};
	return null
}
